import {createSlice} from '@reduxjs/toolkit'

//创建 slice 对象
const todoSlice = createSlice({
  name: 'todo',
  initialState: [
    {
      id: 1,
      title: '做核酸',
      done: false
    },
    {
      id: 2,
      title: '邮寄产品',
      done: true
    }
  ],
  reducers: {
    //新增 {type: 'todo/addTodo', payload: {id: xxx, title: xx, done: false}}
    addTodo: (state, action) => {
      //直接修改
      state.push(action.payload);
    },
    //更新  {type: 'todo/checkTodo', payload: {id: 2, done: false}}
    checkTodo: (state, action) => {
      state.forEach(item => {
        if(item.id === action.payload.id){
          //修改当前任务的 done 属性值
          item.done = action.payload.done;
        }
      })
    },
    //移除  {type: 'todo/removeTodo', payload: 3}
    removeTodo: (state, action) => {
      let index = state.findIndex(item => item.id === action.payload)
      state.splice(index, 1);
    },
    // 批量更新完成状态  {type: 'todo/checkAllTodo',  payload: true}
    checkAllTodo: (state, action) => {
      //更改
      state.forEach(item => {
        item.done = action.payload;
      })
    },
    //批量删除已经完成的任务 {type: 'todo/removeDoneTodo', payload: undefined}
    removeDoneTodo: (state, action) => {
      let index = 0;
      while(index < state.length){
        //如果当前任务已经完成
        if(state[index].done){
          //删除
          state.splice(index, 1);
        }else{
          index += 1
        }
      }
    }
  }
});

//获取并暴露 action creator
export let {addTodo, removeTodo, checkTodo, checkAllTodo, removeDoneTodo} = todoSlice.actions;

//暴露 reducer 函数
export default todoSlice.reducer;
